package com.service;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.atomic.AtomicInteger;


@Service
public class MiaoshaService {


    @Autowired
    private RedisTemplate redisTemplate;

    private AtomicInteger atomicInteger=new AtomicInteger(10);

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 这个不行，会超卖
     */
    public void mianshaNoLock(){
        //从redis中取出goots的
        Integer goods=(Integer)redisTemplate.boundValueOps("goods").get();
        if (goods>0){
            goods--;
            System.out.println(goods);

            redisTemplate.boundValueOps("goods").set(goods);
        }


    }


    public void mianshaNoLock1(){
        //从redis中取出goots的
        Integer goods=(Integer)redisTemplate.boundValueOps("goods").get();
        if (goods>0){

            int newGoosd=atomicInteger.decrementAndGet();
            System.out.println(newGoosd);

            redisTemplate.boundValueOps("goods").set(newGoosd);
        }


    }

    /**
     * 单服务器解决方案
     */
    public synchronized void mianshaNoLock2(){
        //从redis中取出goots的
        Integer goods=(Integer)redisTemplate.boundValueOps("goods").get();
        if (goods>0){

            int newGoosd=atomicInteger.decrementAndGet();
            System.out.println(newGoosd);

            redisTemplate.boundValueOps("goods").set(newGoosd);
        }


    }


    /**
     *集群环境
     */
    public void mianshaNoLock3(){
        RLock rLock=redissonClient.getLock("miansha");
        rLock.lock(); //一直等待

        //从redis中取出goots的数量
        Integer goods=(Integer)redisTemplate.boundValueOps("goods").get();
        if (goods>0){

            int newGoosd=atomicInteger.decrementAndGet();
            System.out.println(newGoosd);

            redisTemplate.boundValueOps("goods").set(newGoosd);
        }
        rLock.unlock();


    }

}
